<?php
namespace Admin\Model;
class ApiUsersModel extends \Think\Model{

    //表名
    public $tableName = 'api_users';

    //自动完成
    protected $_auto = array(
        //array(填充字段,填充内容,[填充条件,附加规则])
        array('create_time', 'time', 1, 'function'),
    );

    //验证
    protected $_validate = array(
        //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
        array('account', 'require', '账号不能为空'),
        array('account','','账号已经存在', 0, 'unique', 3),
        array('app_id', 'require', '应用ID不能为空'),
        array('app_id','','应用ID已经存在', 0, 'unique', 3),
        array('app_secret', 'require', '应用秘钥不能为空'),
    );

    //添加
    public function addData()
    {
        if ($this->create()) {
            if ($this->add()) {
                return true;
            } else {
                $this->error = '添加失败';
            }
        }
    }

    //修改
    public function editData()
    {
        if ($this->create()) {
            if (false !== $this->save()) {
                return true;
            } else {
                $this->error = '修改失败';
            }
        }
    }

    //删除
    public function delData()
    {
        $rid = I('api_user_id', 0, 'trim');
        if ($this->delete($rid)) {
            return true;
        } else {
            $this->error = '删除失败';
        }
    }

    /**
     * 设置添加用户API
     * @param int $userid 用户userid
     * @param int $status 审核状态
     * @return mixed
     */
    public function addMemerApiUser($userid, $status) {
        //$member = $this->where(array('userid'=>$id))->find();
        $account = 'member_'.$userid;
        $count = $this->where(array('account'=>$account))->count();
        if(!$count) {
            $data = array('appId'=>'', 'appSecret'=>'');
            if(!empty($account)) {
                $appId = sha1(md5("open_{$account}_open.joojtech.com"));
                $appSecret = hash_hmac('sha1', $appId , 'joojtech');
                $data = array(
                    'account' => $account,
                    'app_id' => $appId,
                    'app_secret' => $appSecret,
                    'create_time' => time(),
                    'api_user_status' => 1,
                );
            }
            $this->add($data);
        }
        else {
            $this->where(array('account'=>$account))->save(array('api_user_status' => (int)$status));
        }
        return true;
    }
}
